<template>
  <div class="order-menu">
    <el-row :gutter="16">
      <!-- 左侧菜品列表 -->
      <el-col :span="18">
        <el-card
          v-for="c in grouped"
          :key="c.id"
          class="category-card"
          shadow="never"
        >
          <template #header>
            <span class="category-title">{{ c.name }}</span>
          </template>

          <el-row :gutter="12">
            <el-col
              v-for="d in c.dishes"
              :key="d.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
            >
              <el-card class="dish-card" :body-style="{ padding: '8px' }">
                <img
                  v-if="d.image_url"
                  :src="d.image_url"
                  class="dish-img"
                />
                <div v-else class="dish-img empty">无图</div>

                <div class="info">
                  <h4>{{ d.name }}</h4>
                  <p class="price">¥{{ d.price.toFixed(2) }}</p>

                  <!-- 加减按钮 -->
                  <div class="dish-ctrl">
                    <el-button
                      size="small"
                      :disabled="cart.quantityOf(d.id) <= 0"
                      @click="cart.decrement(d.id)"
                    >-</el-button>

                    <span class="qty">{{ cart.quantityOf(d.id) }}</span>

                    <el-button
                      size="small"
                      :disabled="cart.quantityOf(d.id) >= d.stock"
                      @click="cart.increment(d)"
                    >+</el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 右侧购物车 -->
      <el-col :span="6">
        <el-card class="cart-card" shadow="never">
          <template #header>
            <span>购物车</span>
            <el-button text size="small" @click="clearCart">清空</el-button>
          </template>

          <el-empty v-if="cart.items.length === 0" description="空空如也" />

          <div v-else>
           <el-select
  v-model="selectedTableId"
  placeholder="请选择桌台"
  style="width: 100%; margin-bottom: 12px"
>
  <el-option
    v-for="t in tables"
    :key="t.id"
    :label="`${t.tableNumber} (${t.status === 'FREE' ? '空闲' : '占用'})`"
    :value="t.id"
    :disabled="t.status !== 'FREE'"
  />
</el-select>

            <div
              v-for="d in dishes"
              :key="d.id"
              v-show="cart.quantityOf(d.id) > 0"
              class="cart-item"
            >
              <span>{{ d.name }}</span>

              <div style="display: flex; align-items: center">
                <el-button
                  :disabled="cart.quantityOf(d.id) <= 0"
                  size="small"
                  @click="cart.decrement(d.id)"
                >-</el-button>

                <span style="margin: 0 6px; min-width: 24px; text-align: center">
                  {{ cart.quantityOf(d.id) }}
                </span>

                <el-button
                  :disabled="cart.quantityOf(d.id) >= d.stock"
                  size="small"
                  @click="cart.increment(d)"
                >+</el-button>
              </div>

              <span>¥{{ (d.price * cart.quantityOf(d.id)).toFixed(2) }}</span>
            </div>

            <el-divider />
            <div class="cart-total">
              <span>合计</span>
              <strong>¥{{ cart.totalAmount.toFixed(2) }}</strong>
            </div>
            <el-button
              type="primary"
              style="width: 100%; margin-top: 12px"
              :loading="checkingOut"
              @click="checkout"
            >
              去结算
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useCartStore } from '@/stores/cart'
import { submitOrder } from '@/api/order'
import { listTables } from '@/api/table'
import type { Dish } from '@/stores/cart'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useCustomerStore } from '@/stores/customer'
import axios from 'axios'

/* ---------- 类型定义 ---------- */
interface Category {
  id: number
  name: string
  dishes?: Dish[]
}
interface TableItem {
  id: number
  tableNumber: string
  status: 'FREE' | 'OCCUPIED'
}

/* ---------- 数据 ---------- */
const dishes        = ref<Dish[]>([])
const categories    = ref<Category[]>([])
const tables        = ref<TableItem[]>([])
const selectedTableId = ref<number>()
const cart          = useCartStore()
const router        = useRouter()
const checkingOut   = ref(false)
const authStore     = useAuthStore()
const customerStore = useCustomerStore()

/* 当前门店 */
const storeId = computed(() => customerStore.store?.id)

/* ---------- 接口 ---------- */
async function fetchDishes() {
  if (!storeId.value) return
  try {
    const { data } = await axios.get('/api/menu', { params: { storeId: storeId.value } })

    const base = 'http://localhost:8080'   // ← 改成你的后端地址或环境变量

    data.dishes.forEach((d: any) => {
      console.log('原始imageUrl', d.imageUrl)
      console.log('拼接后', base + d.imageUrl)
    })
    dishes.value = data.dishes.map((d: any) => ({
      id: d.id,
      name: d.name,
      price: Number(d.price),
      stock: d.stock,
      category_id: d.categoryId,
      image_url: d.imageUrl && !d.imageUrl.startsWith('http')
        ? base + d.imageUrl
        : d.imageUrl || ''
    }))
    categories.value = data.categories.map((c: any) => ({ id: c.id, name: c.name }))
  } catch {
    ElMessage.error('获取菜品失败')
  }
}

/* ---------- 计算属性 ---------- */
const grouped = computed<Category[]>(() =>
  categories.value.map(c => ({
    ...c,
    dishes: dishes.value.filter(d => d.category_id === c.id)
  }))
)

/* ---------- 购物车操作 ---------- */
function clearCart() {
  cart.clear()
  selectedTableId.value = undefined
}

/* ---------- 下单 ---------- */
async function checkout() {
  if (!selectedTableId.value) {
    ElMessage.warning('请选择桌台')
    return
  }
  if (cart.items.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }
  if (checkingOut.value) return
  checkingOut.value = true

  const param = {
    userId: authStore.userId,
    storeId: storeId.value,
    tableId: selectedTableId.value,
    items: cart.items.map(i => ({
      dishId: i.dishId,
      quantity: i.quantity
    }))
  }

  try {
    const { data: res } = await submitOrder(param)
    ElMessage.success('下单成功')
    router.push({ name: 'Pay', params: { orderId: res.data } })
    clearCart()
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '下单失败')
  } finally {
    checkingOut.value = false
  }
}

/* ---------- 生命周期 ---------- */
onMounted(async () => {
  customerStore.loadStore()
  if (!storeId.value) {
    ElMessage.warning('请先选择门店')
    router.replace('/customer/select-store')
    return
  }
  await fetchDishes()
  const { data } = await listTables(storeId.value!)
tables.value = data // ✅ 不再过滤，只展示全部
})
</script>

<style scoped>
.order-menu {
  padding: 16px;
}
.category-card {
  margin-bottom: 16px;
}
.category-title {
  font-size: 18px;
  font-weight: bold;
}
.dish-card {
  margin-bottom: 12px;
}
.dish-img {
  width: 100%;
  height: 120px;        /* 你原来写死的高度保留 */
 object-fit: contain;
background: #f5f5f5;   /* 留白区域加底色 */
  border-radius: 4px;
}
.dish-img.empty {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #999;
}
.info {
  padding-top: 8px;
}
.price {
  color: #f56c6c;
  margin: 4px 0 8px;
}
.cart-card {
  position: sticky;
  top: 16px;
}
.cart-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 14px;
}
.cart-total {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
}
.dish-ctrl {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 6px;
}
.qty {
  min-width: 24px;
  text-align: center;
  font-weight: bold;
}
</style>